package com.example.jflow.investment.web;

import com.alibaba.fastjson.JSONArray;
import com.cmb.xft.open.api.HttpResponseData;
import com.cmb.xft.open.api.Sm4Util;
import com.cmb.xft.open.api.XftOpenApiReqClient;
import com.example.jflow.investment.po.BaseReqInfList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.jflow.investment.po.Result;
import com.example.jflow.investment.po.SalaryResultDataList;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;

@RestController
@RequestMapping("/InvestmentWeb")
@Slf4j
public class InvestmentWeb {

    private static final String companyId = "AAB72047";
    private static final String appId = "2f1ffd26-907b-4d99-b3b9-89ec99ef64fd";
    private static final String authoritySecret = "00f21d4513844bec6116a64c375b08937a16fd11e4b7b425b82a92f2d9e9685ede";
    private static final String usrNbr = "U0000";
    private static final String usrUid = "AAB72047";
    /**
     * 发票影像采集(新)
     */
    @PostMapping("/getMultipart")
    public Object getMultipart(@RequestParam("file") MultipartFile file, BaseReqInfList baseReqInf) throws Exception{
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = "https://api.cmbchina.com/xft/fnc/xft-invoicein/v1/enter-invoice/multipart-file";
        /* 2.公共信息构建 */
        baseReqInf.setUsrNbr("U0000");
        baseReqInf.setUsrUid("AUTO0001");
        baseReqInf.setAppId(appId);
        baseReqInf.setAuthoritySecret(authoritySecret);
        baseReqInf.setCompanyId(companyId);
        String queryString =baseReqInf.getRequestBody();
//        String queryString = "{\"enterUserNumber\":\"U0000\"}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData result = XftOpenApiReqClient.doFileUploadByFileReq(baseReqInf, url, queryParam, file);
        String responseBody = result.getBody();
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            return responseBody;
        } catch (Exception e) {
            System.out.println("解密失败：" + responseBody);
        }
        return responseBody;
    }
    //查询已采集进项发票
    @PostMapping("/getYcjjxfp")
    public Object getYcjjxfp(BaseReqInfList baseReqInf) throws Exception{
        String url = "https://api.cmbchina.com/xft/fnc/xft-invoicein/v1/invoice-in/query-enter-invoice";
        baseReqInf.setUrl(url);
        return General(baseReqInf);
    }
    //薪资查询
    @PostMapping("/getSalary")
    public Object getSalary(BaseReqInfList baseReqInf) throws Exception{
        baseReqInf.setUrl("https://api.cmbchina.com/sal/sal/xft-sly/salary/api/query-salary-result");
//        Result result = new Result();
//        String rval = General(baseReqInf);
//        ObjectMapper mapper = new ObjectMapper();
//        JsonNode jsonNode = mapper.readTree(rval);
//        Object data = new Object();
//        if (jsonNode.has("body") && !jsonNode.get("body").isNull()) {
//            JsonNode jsonString = jsonNode.get("body");
//            JsonNode itemsNode = jsonString.path("salaryResultDataList");
//            StringBuilder sb1 = new StringBuilder();
//            List<String> strs= new ArrayList<>();
//            if (itemsNode.isArray()) {
//                List<SalaryResultDataList> salaryResultDataLists = convertJsonToList(itemsNode, SalaryResultDataList.class);
//                for(int i =0;i<salaryResultDataLists.size();i++){
//                    SalaryResultDataList salaryResultDataList = salaryResultDataLists.get(i);
//                    if(salaryResultDataList != null){
//                        strs.add(salaryResultDataList.getSalaryResultData());
//                        sb1.append(salaryResultDataList.getSalaryResultData());
//                        if (i < salaryResultDataLists.size() - 1) {
//                            sb1.append(",");
//                        }
//                        data = sb1.toString();
//                    }
//                }
//            }
//        }
//        result.setStatus(200);
//        result.setMessage("成功");
//        result.setData(data);
//        return result;
        return General(baseReqInf);
    }
    //单据数据推送
    @PostMapping("/getDjts")
    public Object getDjts(BaseReqInfList baseReqInf) throws Exception{
        baseReqInf.setUrl("https://api.cmbchina.com/xft/fnc/accounting-document/document/classic/v1/put");
        return General(baseReqInf);
    }
    //查询账套信息
    @PostMapping("/selectAccountingBook")
    public Object selectAccountingBook(BaseReqInfList baseReqInf) throws Exception{
        String url = "https://api.cmbchina.com/xft/fnc/xft-fbk/account-set/account-set-list";
        baseReqInf.setUrl(url);
        return General(baseReqInf);
    }
    //查询科目列表
    @PostMapping("/selectItemList")
    public Object selectItemList(BaseReqInfList baseReqInf) throws Exception{
        String url = "https://api.cmbchina.com/xft/fnc/xft-fbk/basic/item/item-list-redis";
        baseReqInf.setUrl(url);
        return General(baseReqInf);
    }
    //查询凭证列表
    @PostMapping("/selectVoucherList")
    public Object selectVoucherList(BaseReqInfList baseReqInf) throws Exception{
        String url = "https://api.cmbchina.com/xft/fnc/xft-fbk/voucher/query-voucher-api";
        baseReqInf.setUrl(url);
        return General(baseReqInf);
    }
    //新建通用申请单
    @PostMapping("/createApply")
    public Object createApply(BaseReqInfList baseReqInf) throws Exception{
        String url = "https://api.cmbchina.com/itrip/xft-api/v1/bills/apply/common/create";
        baseReqInf.setUrl(url);
        return General(baseReqInf);
    }
    //新建日常报销单
    @PostMapping("/createReimburse")
    public Object createReimburse(BaseReqInfList baseReqInf) throws Exception{
        String url = "https://api.cmbchina.com/itrip/xft-api/v1/reimburse/bill/create";
        baseReqInf.setUrl(url);
        return General(baseReqInf);
    }
    public String General(BaseReqInfList baseReqInf) throws Exception{
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        baseReqInf.setUsrNbr(usrNbr);
        baseReqInf.setUsrUid(usrUid);
        baseReqInf.setAppId(appId);
        baseReqInf.setAuthoritySecret(authoritySecret);
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        String requestBody =baseReqInf.getRequestBody();
        String secretMsg = Sm4Util.encryptEcb(key, requestBody);
        Map<String, String> newRequestBodyMap = new HashMap<>();
        // secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData result = XftOpenApiReqClient.doCommonPostReq(baseReqInf, baseReqInf.getUrl(), queryParam, requestBody);
        String responseBody = result.getBody();
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            return responseBody;
        } catch (Exception e) {
            System.out.println("解密失败：" + responseBody);
        }
        return responseBody;
    }
    private static final ObjectMapper mapper = new ObjectMapper();
    public static <T> List<T> convertJsonToList(JsonNode node, Class<T> valueType) {
        try {
            return mapper.convertValue(node,
                    mapper.getTypeFactory().constructCollectionType(List.class, valueType));
        } catch (IllegalArgumentException e) {
            return new ArrayList<>();
        }
    }

}
